//
//  StatusRefreshControl.swift
//  MySinaWeiBo
//
//  Created by zhangfuwei on 15/8/9.
//  Copyright © 2015年 zhangfuwei. All rights reserved.
//

import UIKit

class StatusRefreshControl: UIRefreshControl {

    // MARK: 重写构造函数
    override init() {
        
        super.init()
        setupUI()

    }

    // MARK: 重写endRefreshing方法
    override func beginRefreshing() {
        super.beginRefreshing()
        refreshView.startloading()
    }
    
    override func endRefreshing() {
        super.endRefreshing()
        refreshView.stoploading()
    }

    
    // MARK: 在销毁的时候要移除观察者
    deinit {
        self.removeObserver(self, forKeyPath: "frame", context: nil)
    }
    
    // MARK: 重写观察属性变化函数
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {

        if frame.origin.y > 0 {
            return
        }
        
        //  如果系统的刷新为 true,则播放刷新动画
        if refreshing {
            refreshView.startloading()
        }
        //  如果达到指定偏移量,则剪头方向向上
        if frame.origin.y < -60 && !refreshView.rotateFlag {
            print("向上翻")
           
            refreshView.rotateFlag = true
        }
        
        if frame.origin.y > -60 && refreshView.rotateFlag{
            print("向下翻")
            refreshView.rotateFlag = false
        }
    
    }
    
    // MARK: 设置 UI 界面
    func setupUI() {
        // KVO 观察属性 frame 变化
        self.addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
        
        
        tintColor = UIColor.clearColor()
        //  添加控件
        addSubview(refreshView)
        //  设置约束
        refreshView.ff_AlignInner(type: ff_AlignType.CenterCenter, referView: self, size: refreshView.bounds.size)
        
    }
    
    //  懒加载控件
    lazy var refreshView = StatusRefreshView.refreshView()
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

///  自定义一个 view 类
// MARK: 下拉刷新控件
class StatusRefreshView: UIView {
    
  
    private var rotateFlag : Bool = false {
        didSet {
            rotateTip()
        }
    }
    
    @IBOutlet weak var loadingIcon: UIImageView!

    @IBOutlet weak var tipView: StatusRefreshView!
    
    @IBOutlet weak var tipIcon: UIImageView!
    
    
    //  从xib 加载view
    class func refreshView() ->StatusRefreshView {
    
        return NSBundle.mainBundle().loadNibNamed("StatusRefreshView", owner: nil, options: nil).last as! StatusRefreshView
    
    }
    //  开始 loading 视图
    func startloading() {
        
        //  先判断当前loading 动画是否存在
        if loadingIcon.layer.animationForKey("loading") != nil  {
            return
        }
        
        //  隐藏 tipView 视图
        tipView.hidden = true
        //  旋转 loadingIcon 
        
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        anim.duration = 0.5
        anim.toValue = M_PI * 2
        anim.repeatCount = MAXFLOAT
        loadingIcon.layer.addAnimation(anim, forKey:"loading")
        
    }
    
    //  旋转箭头的函数
    func rotateTip() {
        let angle = rotateFlag ? CGFloat(M_PI - 0.01):CGFloat(M_PI + 0.01)
        
        UIView.animateWithDuration(0.25) { () -> Void in
            self.tipIcon.transform = CGAffineTransformRotate(self.tipIcon.transform, angle)
        }
    }
    
    //  停止 loading 加载
    func stoploading() {
        
        tipView.hidden = false
        
        loadingIcon.layer.removeAllAnimations()
    }
}